//
//  ReuseImageViewAndTextFieldTableViewCell.swift
//  House
//
//  Created by 吕品 on 16/7/1.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

import UIKit
public protocol MixViewProtocol: NSObjectProtocol {
    func didPassValue(isSure: Bool) -> Void
}
class ReuseImageViewAndTextFieldTableViewCell: UITableViewCell {

    public var mixView = ImageViewAndTextFieldMixView()
    private var time = 60
    private var timer = Timer()
    var isSure = false

    weak var delegate: MixViewProtocol?

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.mixView = ImageViewAndTextFieldMixView.init(frame: self.contentView.frame)
        self.contentView.addSubview(mixView)
        mixView.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsetsMake(0, 0, 0, 0))
        }
        mixView.codeButton.tintColor = UIColor.white
        mixView.codeButton.addTarget(self, action: #selector(didTouchButton(_:)), for: .touchUpInside)
        mixView.codeButton.setTitle("获取验证码", for: .normal)
    }

    @objc fileprivate func didTouchButton(_ button: UIButton) -> Void {
        if isSure {
            time = 60
            timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeDecrease), userInfo: nil, repeats: true)
            RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
            button.isEnabled = false
        }
        self.delegate?.didPassValue(isSure: isSure)
    }
    @objc fileprivate func timeDecrease() -> Void {
        DispatchQueue.main.async(execute: {
            self.mixView.codeButton.setTitle(self.time.description + "秒后重新获取", for: .normal)
        })
        time -= 1
        if time == 0 {
            DispatchQueue.main.async(execute: { 
                self.mixView.codeButton.setTitle("获取验证码", for: .normal)
                self.mixView.codeButton.isEnabled = true
                self.timer.invalidate()
            })
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
}
